package com.haixiaoke.saas.enterprise.basedata.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.haixiaoke.saas.apartment.domain.ServiceFacilities;
import com.haixiaoke.saas.apartment.service.IServiceFacilitiesService;
import com.haixiaoke.saas.common.annotation.Anonymous;
import com.haixiaoke.saas.common.core.domain.AjaxResult;
import com.haixiaoke.saas.common.core.domain.entity.SysDictData;
import com.haixiaoke.saas.system.BaseController;
import com.haixiaoke.saas.system.service.ISysDictTypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

@RestController
@RequestMapping("/enterprise/base-data")
public class EnterpriseBaseDataController extends BaseController {

    @Autowired
    private IServiceFacilitiesService serviceFacilitiesService;
    @Autowired
    private ISysDictTypeService dictTypeService;

    /**
     * 查询服务设施列表
     */
    @Anonymous
    @GetMapping("/service-facilities/options")
    public AjaxResult serviceFacilitiesOptions(ServiceFacilities serviceFacilities) {
        List<ServiceFacilities> facilities = serviceFacilitiesService.selectHouseFacilitiesList(serviceFacilities);
        if (CollUtil.isEmpty(facilities)) {
            return AjaxResult.success();
        }
        List<SysDictData> dict = dictTypeService.selectDictDataByType("facilities_type");
        if (CollUtil.isEmpty(dict)) {
            return AjaxResult.success();
        }

        Map<String, List<Map<String, Object>>> categorizedFacilities = new LinkedHashMap<>();
        Map<String, String> typeMapping = new LinkedHashMap<>();

        dict.forEach(dictData -> {
            typeMapping.put(dictData.getDictValue(), dictData.getDictLabel());
        });

        for (String type : typeMapping.values()) {
            categorizedFacilities.put(type, new ArrayList<>());
        }

        for (ServiceFacilities facility : facilities) {
            String category = typeMapping.get(facility.getFacilitiesType());
            if (StrUtil.isNotBlank(category)) {
                Map<String, Object> facilityLabelValue = new HashMap<>();
                facilityLabelValue.put("label", facility.getFacilitiesName());
                facilityLabelValue.put("value", facility.getFacilitiesId());
                categorizedFacilities.get(category).add(facilityLabelValue);
            }
        }
        Map<String, List<Object>> categoryOptions = new LinkedHashMap<>();
        for (String type : typeMapping.values()) {
            categoryOptions.put(type, new ArrayList<>());
        }

        Map<String, Object> map = new HashMap<>();
        map.put("categorizedFacilities", categorizedFacilities);
        map.put("categoryOptions", categoryOptions);

        return success(map);
    }

}